import { defineStore } from 'pinia';
import { screenApi }  from '/@/api/screen'; // 假设是 Wtm 框架的请求工具
import { AxiosResponse } from 'axios';





// 定义大屏数据的接口类型
interface Screen {
  id: string | number;
  name: string;
  [key: string]: any; // 允许其他任意属性
}


// 定义 Pinia Store（命名规范：useXXXStore）
export const useScreenStore = defineStore('screen', {
  state: (): {
    currentScreen: Screen | null;
    screenList: Screen[];
    loading: boolean;
    error: string | null;
  } => ({
    currentScreen: null, // 当前编辑的大屏
    screenList: [],      // 大屏列表
    loading: false,      // 加载状态
    error: null          // 错误信息
  }),
  
  actions: {
    // 1. 创建新大屏
    async createScreen(screenData: Omit<Screen, 'id'>): Promise<AxiosResponse<Screen>|any> {
      this.loading = true;
      this.error = null;
      try {
        const response = await screenApi().get(screenData.id);       
              
        if (response.success && response.data) {
          this.currentScreen = response.data;
          return response;
        } else {
          this.error = response.message || '创建大屏失败';
          return response;
        }
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : '创建大屏时发生错误';
        this.error = errorMessage;
       
      } finally {
        this.loading = false;
      }
    },

    // 2. 更新大屏
    async updateScreen(screenData: Screen): Promise<AxiosResponse<Screen>|any> {
      this.loading = true;
      this.error = null;
      try {
        const response = await  screenApi().edit({    
          data: screenData
        });
        
        if (response.success && response.data) {
          this.currentScreen = response.data;
          return response;
        } else {
          this.error = response.message || '更新大屏失败';
          return response;
        }        
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : '更新大屏时发生错误';
        this.error = errorMessage;
      
      } finally {
        this.loading = false;
      }
    
    },

    // 3. 根据 ID 获取大屏
    async getScreenById(screenId: string | number): Promise<AxiosResponse<Screen>|any> {
      this.loading = true;
      this.error = null;
      try {
        const response = await screenApi().get(screenId);              
        if (response.success && response.data) {
          this.currentScreen = response.data;
          return response;
        } else {
          this.error = response.message || '获取大屏失败';
          return response;
        }
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : '获取大屏时发生错误';
        this.error = errorMessage;
        
      } finally {
        this.loading = false;
      }
    }
  }
});
